//
//  string.cpp
//  learnC++
//
//  Created by apple on 2018/5/24.
//  Copyright © 2018年 yunfan.com. All rights reserved.
//

#include "string.hpp"
#define __STDC_WANT_LIB_EXT1__ 1


void stringTest(){
    
    
    string_length();
    
    string_nomal();
    
    std::string myname("alex");
    
    //保留前2位
//    myname.resize(2);
    
    //把字符串设为8位，不足的用‘x’补齐
    myname.resize(8, 'x');
    
    //字符数组
    std::string namess[] = {"jack","rose","lili"};
    
    std::string name3[]{"jackma","mahua","teng"};
    
//    std::wstring name4("jack");
    
    namess[0].push_back('c');
    
    
    //重新赋值
    myname = "jack";
    std::cout << myname << std::endl;
    
    
//    myname.insert(2, "str");
//    myname.clear();
//    myname.replace(2, 2, "xx");
    myname.replace(myname.find("j"), 1, "1");
    //append
    std::string other_name(",rose");
    
    myname += other_name;
    
    std::cout << myname << std::endl;
    
    std::string m = myname.substr(0,3);
    
    //length
    std::cout << "length = " << myname.length() <<std::endl;
    
    //字符串转数字
    
    std::string num{"123"};
    int res;
    
    std::stringstream ss;
    ss << num;
    ss >> res;
    std::cout << res << std::endl;
}

void string_length(){
    
    char myString[] = "string";//实际上是"'s''t''r''i''n''g''\0'"  注意\0为1个字符不是2个 和数组的特性一致，只能修改大个元素
    myString[1] = 'p';
    
    int length = sizeof(myString) / sizeof(myString[0]);
    std::cout << myString<< " has " << length << " characters.\n";//长度为字符个数+1
    
    //字符长度-数组大小
    char name[20] = "Alex"; // only use 5 characters (4 letters + null terminator)
    std::cout << "My name is: " << name << '\n';
    std::cout << name << " has " << strlen(name) << " letters.\n";
    std::cout << name << " has " << sizeof(name) / sizeof(name[0]) << " characters in the array.\n";
    std::cout << sizeof(int)<< "\n";
}

void string_nomal(){
    char source[50] = "copy this";
    char des[50];//必须必要复制的内存大
    strcpy(des, source);
    
    std::cout << des <<std::endl;
    
    //可以使用系统自带的
    size_t len = strlen(source);
    std::cout << len << "\n";
    
//    int res = strcmp(source, des);
//    std::cout << res << "KKKKK\n";
    
    
//    //拼接
    strcat(source, des);
    printf("source = %s\n",source);//返回结果在source中
    char str[] = "kitty";
    strncat(source, str, 4);//source必须有足够的内存来拼接，否则会崩溃
    
    std::cout << source << "\n";
    
//    int res = strncmp(source, des, 20);
//    std::cout << res << "KKKKK\n";
    
}

